package parser;

import java.io.File;
import java.util.LinkedList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class EntityWriter {
	
	private Document doc;
	private Element rootElement;
	
	public EntityWriter() {
		try{
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			// root element
			doc = docBuilder.newDocument();
			rootElement = doc.createElement("Entities");
			doc.appendChild(rootElement);
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		}
	}
	
	public void addToTree(LinkedList<EntityElement> list) {
		for(EntityElement element : list) {
			// entity element
			Element entity = doc.createElement("Entity");
			rootElement.appendChild(entity);
			// set attribute to entity element
			Attr attr = doc.createAttribute("type");
			switch(element.getType()){
				case NAME:
					attr.setValue("nr");
					break;
				case LOCATION:
					attr.setValue("ns");
					break;
				case ORGANIZATION:
					attr.setValue("nt");
					break;
			}
			entity.setAttributeNode(attr);
			// text element
			Element text = doc.createElement("Text");
			text.appendChild(doc.createTextNode(element.getElement()));
			entity.appendChild(text);
		
			// doc element
			Element docID = doc.createElement("Doc");
			docID.appendChild(doc.createTextNode(""+element.getDocID()));
			entity.appendChild(docID);
			
			// start index element
			Element ind = doc.createElement("Start");
			ind.appendChild(doc.createTextNode(""+element.getStartIndex()));
			entity.appendChild(ind);
		}
	}
	
	public void writeFinalFile() {
		try {
			// write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File("out.xml"));
		
			// Output to console for testing
			// StreamResult result = new StreamResult(System.out);
		
			transformer.transform(source, result);
		} catch (TransformerException tfe) {
			tfe.printStackTrace();
		}
	}

}
